package com.hansming.bss.modules.sfc.wxpay;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;





import com.hansming.bss.common.utils.IdGen;
import com.hansming.bss.common.web.BaseController;
import com.hansming.bss.modules.sfc.entity.Order;
import com.hansming.bss.modules.sfc.entity.WxUser;
import com.hansming.bss.modules.sfc.service.OrderService;
import com.hansming.bss.modules.sfc.service.WxUserService;
import com.hansming.bss.modules.sfc.util.IpUtils;




/**
 * 生成签名Controller
 * @author YankeesJ
 * @version 2017-11-29
 */



@Controller
@RequestMapping(value = "pay/wxpay")
public class CreatSign extends BaseController{
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private WxUserService wxuserService;


	//设置请求器的配置
	@RequestMapping(value = "")
//	public @ResponseBody Map<String, Object> wxPay(HttpServletRequest request,HttpServletResponse response,String orderid){
	public @ResponseBody Map<String, Object> wxPay(HttpServletRequest request,HttpServletResponse response){
		try{  
			
		/*	商品名称
			订单号
			支付金额*/
//			String orderid = "400baab14232486298d2d4ae64609fe3";
			String orderid = (String)request.getSession().getAttribute("orderid");
			Order order=new Order();
			order=orderService.getsgin(orderid);
			if(order.getState().equals("1")) {
			
	            //生成的随机字符串  
	            String nonce_str = IdGen.uuid();  
	            //商品名称
	//            String body = "test";
	            String body = order.getProductname();
	            
	//            String out_trade_no="20180228125390"; 
	            String out_trade_no =  String.valueOf(order.getWxnum());
	            
	            BigDecimal bd = new BigDecimal("100");
	            
	            String total_fee=String.valueOf(order.getPrice().multiply(bd).intValue()); 
	
	            //获取客户端的ip地址  
	            String spbill_create_ip = IpUtils.getIpAddr(request);  
	            
	            System.out.println("ip======>"+spbill_create_ip);
	              
	            //组装参数，用户生成统一下单接口的签名  
	            Map<String, String> packageParams = new HashMap<String, String>();  
	            packageParams.put("appid", WxPayConfig.appid);  
	            packageParams.put("mch_id", WxPayConfig.mch_id);  
	            packageParams.put("nonce_str", nonce_str);  
	            packageParams.put("body", body); 
	            packageParams.put("out_trade_no", out_trade_no);//商户订单号
	            packageParams.put("total_fee", total_fee);//支付金额，这边需要转成字符串类型，否则后面的签名会失败
	//            packageParams.put("total_fee", total_fee);//支付金额，这边需要转成字符串类型，否则后面的签名会失败,金额不能出现小数点，且已分为单位
	            packageParams.put("spbill_create_ip", spbill_create_ip);  
	            packageParams.put("notify_url", WxPayConfig.notify_url);//支付成功后的回调地址  
	//            packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式              
	            packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式
	            
	                String prestr = PayUtils.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串   
	                System.out.println("prestr="+prestr);
	                //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口  
	                String mysign = PayUtils.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();  
	                /*prestr=prestr+"&key="+WxPayConfig.key;
	                System.out.println(prestr);
	                String mysign = PayUtils.creatsign(prestr).toUpperCase();*/
	                
	                System.out.println("mysign="+mysign);
	               /* String mysign = PayUtils.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();*/  
	      
	              
	               
	                /*String xml="<xml><appid>wxbe33a4bd413df686</appid><body>asd</body><mch_id>1283598701</mch_id><nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str><notify_url>http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url><openid>odV0i0R4Yvru75rI98_j4SiqQx8o</openid><out_trade_no>1417129930</out_trade_no><spbill_create_ip>119.137.54.72</spbill_create_ip><total_fee>1</total_fee><trade_type>JSAPI</trade_type><sign>5E4D9FAD3634FC00B56D783EF62CC7A9</sign></xml>";
	*/
	                		
	        
	                    //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去  
	            String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"   
	                    + "<body>"+body+"</body>"   
	                    + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"   
	                    + "<nonce_str>" + nonce_str + "</nonce_str>"   
	
	//                    + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>" 
	
	                    + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"
	
	                    + "<out_trade_no>"+out_trade_no+"</out_trade_no>"   
	                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"   
	                    + "<total_fee>"+total_fee+"</total_fee>"  
	                    + "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"   
	                    + "<sign>" + mysign + "</sign>"  
	                    + "</xml>"; 
	              
	            System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);  
	  
	            //调用统一下单接口，并接受返回的结果  
	            String result = PayUtils.httpRequest(WxPayConfig.pay_url, "POST", xml);  
	              
	            System.out.println("调试模式_统一下单接口 返回XML数据：" + result);  
	              
	            // 将解析结果存储在HashMap中
	            Map map = PayUtils.doXMLParse(result);
	
	            String return_code = (String) map.get("return_code");//返回状态码
	            String code_url=(String) map.get("code_url");//返回下单地址
	
	            System.out.println("------------>return code<------"+return_code);
	            System.out.println("------------>code_url<------"+code_url);
	
	
	
	            String format = "jpg";
	            Hashtable hints = new Hashtable();
	            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	            BitMatrix bitMatrix;
	            try {
	                bitMatrix = new MultiFormatWriter().encode(code_url,BarcodeFormat.QR_CODE,300,300,hints);
	                MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
	            } catch (WriterException e) {
	                e.printStackTrace();
	            } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
			}





        }catch(Exception e){
            e.printStackTrace();
        }
		System.out.println("------------>执行5<------");
        return null;
    }


	

	
}






